package com.agmte.api.common.crud.utils;

import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.apache.logging.log4j.util.Strings;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

public class MapperXmlParser {
    // 匹配MyBatis非纯SQL语法的正则表达式
    private static final Pattern MYBATIS_NON_PURE_SQL_PATTERN = Pattern.compile(
            "(<[a-zA-Z]+(?:\\s+[^>]*)?>)|" + // <if>, <where>等动态标签
                    Pattern.DOTALL
    );

    public static void main(String[] args) throws Exception {
        //String mapperFilePath = "G:\\project\\java\\restructure_dtserver\\restructure_dtserver\\server\\service\\service-table\\src\\main\\java\\com\\oyjl\\utils\\UserMapper.xml";

        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\n" +
                "        \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" +
                "<mapper namespace=\"java.lang.Object\">\n" +
                "\n" +
                "    <select id=\"selectById\" resultType=\"map\">\n" +
                "        SELECT *\n" +
                "        FROM users\n" +
                "        WHERE id = #{id}\n" +
                "ORDER BY ${fileName} \n" +
                "    </select>\n" +
                "</mapper>\n";
        // 1. 创建MyBatis配置
        // 准备参数
        Map<String, Object> params = new HashMap<>();
        params.put("id", 1001);
        params.put("fileName", "tt");

        String sql = parse(xml, "selectById", params);
        System.out.println(sql);


    }

    public static String parseBySql(String selectXml, Map<String, Object> params) throws Exception {
        selectXml = isPureSql(selectXml) ? "<![CDATA[" + selectXml + "]]>" : selectXml;
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\n" +
                "        \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" +
                "<mapper namespace=\"java.lang.Object\">\n" +
                "\n" +
                "    <select id=\"selectById\" resultType=\"map\">\n" +
                selectXml + "\n" +
                "    </select>\n" +
                "</mapper>\n";
        return parse(xml, "selectById", params);
    }

    public static String parseBySelect(String selectXml, Map<String, Object> params) throws Exception {
        // 1. 准备解析器工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringElementContentWhitespace(true); // 忽略空白节点（格式化换行空格）
        DocumentBuilder builder = factory.newDocumentBuilder();

        // 2. 使用 InputSource + StringReader 解析字符串
        InputStream xmlInputStream = new ByteArrayInputStream(selectXml.getBytes(StandardCharsets.UTF_8));
        Document document = builder.parse(xmlInputStream);

        // 3. 获取所有 select 标签
        NodeList selectList = document.getElementsByTagName("select");
        if (selectList.getLength() != 1) {
            throw new Exception("仅支持一个select标签");
        }
        Node item = selectList.item(0);
        String id = item.getAttributes().getNamedItem("id").getNodeValue();
        if(Strings.isBlank(id)){
            throw new Exception("select标签id属性未指定值");
        }
        selectXml = isPureSql(selectXml) ? "<![CDATA[" + selectXml + "]]>" : selectXml;
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\n" +
                "        \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" +
                "<mapper namespace=\"java.lang.Object\">\n" +
                "\n" +
                selectXml + "\n" +
                "</mapper>\n";
        return parse(xml, id, params);
    }

    public static String parseByMapper(String selectXml, Map<String, Object> params) throws Exception {
        selectXml = isPureSql(selectXml) ? "<![CDATA[" + selectXml + "]]>" : selectXml;
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\n" +
                "        \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" +
                "<mapper namespace=\"java.lang.Object\">\n" +
                "\n" +
                selectXml + "\n" +
                "</mapper>\n";
        return parse(xml, "noapi", params);
    }

    public static String parse(String xml, String id, Map<String, Object> params) throws Exception {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
        return parse(inputStream, id, params);
    }

    public static String parse(InputStream inputStream, String id, Map<String, Object> params) throws Exception {
        Path mapperFilePath = saveToXmlFile(inputStream);
        try {
            return parse(mapperFilePath, id, params);
        } catch (Exception e) {
            throw e;
        } finally {
            Files.deleteIfExists(mapperFilePath);
        }
    }

    public static String parse(Path mapperFilePath, String id, Map<String, Object> params) throws Exception {
        Configuration configuration = new Configuration();
        // 解析Mapper.xml
        InputStream inputStream = Files.newInputStream(mapperFilePath);
        XMLMapperBuilder mapperParser = new XMLMapperBuilder(
                inputStream,
                configuration,
                mapperFilePath.toString(),
                configuration.getSqlFragments()
        );
        mapperParser.parse();
        MappedStatement ms = configuration.getMappedStatement(id);
        // 填充参数
        return fillParameters(configuration, ms, params);
    }

    private static String fillParameters(Configuration configuration,
                                         MappedStatement ms,
                                         Object parameterObject) {

        BoundSql boundSql = ms.getBoundSql(parameterObject);
        String sql = boundSql.getSql();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();

        if (parameterMappings != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();

            for (ParameterMapping parameterMapping : parameterMappings) {
                String property = parameterMapping.getProperty();
                Object value;

                if (boundSql.hasAdditionalParameter(property)) {
                    value = boundSql.getAdditionalParameter(property);
                } else if (parameterObject == null) {
                    value = null;
                } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                    value = parameterObject;
                } else {
                    // 简化处理，实际应该使用MetaObject
                    if (parameterObject instanceof Map) {
                        value = ((Map<?, ?>) parameterObject).get(property);
                    } else {
                        try {
                            value = parameterObject.getClass().getDeclaredField(property).get(parameterObject);
                        } catch (Exception e) {
                            value = "UNKNOWN";
                        }
                    }
                }

                // 替换问号
                sql = sql.replaceFirst("\\?", getParameterValue(value));
            }
        }

        return sql;
    }

    private static String getParameterValue(Object value) {
        if (value == null) {
            return "NULL";
        }

        if (value instanceof String) {
            return "'" + value.toString().replace("'", "''") + "'";
        }

        if (value instanceof Date) {
            return "'" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) value) + "'";
        }

        if (value instanceof Number) {
            return value.toString();
        }

        if (value instanceof Boolean) {
            return ((Boolean) value) ? "1" : "0";
        }

        return "'" + value.toString().replace("'", "''") + "'";
    }

    public static Path saveToXmlFile(InputStream inputStream) throws IOException {
        Path outputPath = Paths.get(System.getProperty("user.dir"), UUID.randomUUID() + ".xml");
        // 确保目录存在（可选）
        Files.createDirectories(outputPath.getParent());
        // 直接复制流到文件
        Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);
        return outputPath;
    }

    /**
     * 检查SQL内容是否为纯SQL（无MyBatis特有语法）
     */
    public static boolean isPureSql(String sqlContent) {
        return !Pattern.compile("(<[a-zA-Z]+(?:\\s+[^>]*)?>)", Pattern.DOTALL).matcher(sqlContent).find();
    }

}